package com.hhh.springai_test.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhh.springai_test.common.BaseResponse;
import com.hhh.springai_test.common.ErrorCode;
import com.hhh.springai_test.common.ResultUtils;
import com.hhh.springai_test.constant.UserConstant;
import com.hhh.springai_test.exception.BusinessException;
import com.hhh.springai_test.model.dto.communityPost.AddCommunityPostDTO;
import com.hhh.springai_test.model.dto.communityPost.CategoryStatisticsDTO;
import com.hhh.springai_test.model.dto.communityPost.QueryCommunityPostDTO;
import com.hhh.springai_test.model.dto.communityPost.UpdateCommunityPostDTO;
import com.hhh.springai_test.model.po.CommunityPost;
import com.hhh.springai_test.model.po.CommunityCategory;
import com.hhh.springai_test.model.po.User;
import com.hhh.springai_test.model.vo.CommunityPostVO;
import com.hhh.springai_test.model.vo.UserVo;
import com.hhh.springai_test.service.CommunityPostLikeService;
import com.hhh.springai_test.service.CommunityPostService;
import com.hhh.springai_test.service.CommunityCategoryService;
import com.hhh.springai_test.service.UserService;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/communityPost")
public class CommunityPostController {

    @Resource
    private CommunityPostService communityPostService;

    @Resource
    private UserService userService;

    @Resource
    private CommunityPostLikeService communityPostLikeService;

    @Resource
    private CommunityCategoryService communityCategoryService;

    /**
     * 创建帖子
     * @param addCommunityPostDTO
     * @return
     */
    @PostMapping("/add")
    @SaCheckRole(UserConstant.DEFAULT_ROLE)
    public BaseResponse<Long> addPost(@RequestBody @Valid AddCommunityPostDTO addCommunityPostDTO) {
        long postId = communityPostService.createPost(addCommunityPostDTO);
        return ResultUtils.success(postId);
    }

    /**
     * 删除帖子
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    @SaCheckRole(UserConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> deletePost(@PathVariable Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数不正确");
        }
        Boolean result = communityPostService.HxxRemoveById(id);
        if(!result){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"删除帖子失败了");
        }
        return ResultUtils.success(result);
    }

    /**
     * 更新帖子
     * @param updateCommunityPostDTO
     * @return
     */
    @PostMapping("/update")
    @SaCheckRole(UserConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> updatePost(@RequestBody @Valid UpdateCommunityPostDTO updateCommunityPostDTO) {
        boolean result = communityPostService.updatePost(updateCommunityPostDTO);
        return ResultUtils.success(result);
    }

    /**
     * 根据id获取帖子
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public BaseResponse<CommunityPostVO> getPostById(@PathVariable Long id) {
        // 根据ID获取社区帖子信息
        CommunityPost post = communityPostService.getById(id);
        // 获取帖子的当前浏览量
        Integer viewcount = post.getViewcount();
        // 使用帖子ID的字符串实习对象作为锁对象，确保并发安全下更新浏览量
        synchronized (post.getId().toString().intern()) {
            // 更新浏览量为当前值加1
            post.setViewcount(viewcount+1);
            // 调用服务更新数据库中的浏览量
            communityPostService.updateById(post);
        }
        // 创建社区帖子VO对象，用于封装返回给前端的数据
        CommunityPostVO communityPostVO = new CommunityPostVO();
        // 获取帖子的创建用户ID
        Long createuser = post.getCreateuser();
        // 根据用户ID获取用户信息
        User user = userService.getById(createuser);
        // 将用户信息复制到用户VO中，用于解耦前端和后端的数据模型
        UserVo userVo = BeanUtil.copyProperties(user, UserVo.class);
        // 将帖子信息复制到帖子VO中，同样用于解耦数据模型
        communityPostVO = BeanUtil.copyProperties(post, CommunityPostVO.class);
        // 将用户VO设置到帖子VO中，以便前端可以获取到帖子发布者的相关信息
        communityPostVO.setUserVo(userVo);
        // 返回成功结果，携带帖子VO数据
        return ResultUtils.success(communityPostVO);
    }

    /**
     * 分页获取帖子列表
     * @param queryCommunityPostDTO
     * @return
     */
    @PostMapping("/list")
    public BaseResponse<Page<CommunityPostVO>> listPostByPage(@RequestBody QueryCommunityPostDTO queryCommunityPostDTO) {
        if(queryCommunityPostDTO.getPageSize()>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请走正常页面调用接口");
        }
        Page<CommunityPost> postPage = communityPostService.queryPostPage(queryCommunityPostDTO);
        List<CommunityPost> records = postPage.getRecords();
        ArrayList<CommunityPostVO> postVOS = new ArrayList<>();
        for (CommunityPost record : records) {
            Long createuser = record.getCreateuser();
            User user = userService.getById(createuser);
            UserVo userVo = BeanUtil.copyProperties(user, UserVo.class);
            CommunityPostVO postVO = BeanUtil.copyProperties(record, CommunityPostVO.class);
            postVO.setUserVo(userVo);
            postVOS.add(postVO);
        }
        Page<CommunityPostVO> communityPostVOPage = new Page<>(postPage.getCurrent(), postPage.getSize(), postPage.getTotal());
        communityPostVOPage.setRecords(postVOS);
        return ResultUtils.success(communityPostVOPage);
    }

    /**
     * 获取帖子分类统计信息
     * @return 分类统计信息
     */
    @GetMapping("/category/statistics")
    public BaseResponse<CategoryStatisticsDTO> getCategoryStatistics() {
        // 获取所有分类
        List<CommunityCategory> categories = communityCategoryService.listCategories();
        
        CategoryStatisticsDTO statisticsDTO = new CategoryStatisticsDTO();
        List<CategoryStatisticsDTO.CategoryStatisticsItem> categoryList = new ArrayList<>();
        
        long totalCount = 0;
        
        // 遍历每个分类，统计帖子数量
        for (CommunityCategory category : categories) {
            CategoryStatisticsDTO.CategoryStatisticsItem item = new CategoryStatisticsDTO.CategoryStatisticsItem();
            item.setId(category.getId());
            item.setCategoryCode(category.getCategorycode());
            item.setCategoryNameZh(category.getCategorynamezh());
            
            // 统计该分类下的帖子数量
            long count = communityPostService.count(new LambdaQueryWrapper<CommunityPost>()
                    .eq(CommunityPost::getCategorycode, category.getCategorycode())
                    .eq(CommunityPost::getIsdelete, 0)); // 只统计未删除的帖子
            
            item.setPostCount(count);
            totalCount += count;
            categoryList.add(item);
        }
        
        statisticsDTO.setTotalCount(totalCount);
        statisticsDTO.setCategoryList(categoryList);
        
        return ResultUtils.success(statisticsDTO);
    }
}
